package Dm

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (or TableInfoMeta) TableName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var (
		f1    any
		event = "[oracleTableName]"
	)
	for _, v := range []string{"ALL_TABLES", "DBA_TABLES",} {
		result.BaseResult.Sql = fmt.Sprintf("select "+
			"TABLE_NAME AS \"tableName\" "+
			"from %v "+
			"where "+
			"owner = '%s' %v", v, s.TableInfo.Schema, func() string {
			switch {
			case s.TableInfo.Table == "*":
				return ""
			case strings.Contains(s.TableInfo.Table, "%"):
				return fmt.Sprintf("and table_name like '%v'", s.TableInfo.Table)
			default:
				return fmt.Sprintf("and table_name = '%v'", s.TableInfo.Table)
			}
		}())
		// 执行查询
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.StringGarth,
		}); err != nil || f1 == nil {
			continue
		}
		result.Result = f1.([]string)
		break
	}
	return
}

/*
TableExist Oracle 获取对应的库表信息
*/
func (or TableInfoMeta) TableExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var (
		event = "[oracleTableExist]"
		f1    any
	)
	for _, v := range []string{"ALL_TABLES", "DBA_TABLES"} {
		result.BaseResult.Sql = fmt.Sprintf("select count(*) as \"sum\" from %v where owner = '%s'  and table_NAME = '%s'", v, s.TableInfo.Schema, s.TableInfo.Table)
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil || f1 == nil {
			continue
		}
		if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
			result.Result = true
		} else {
			result.Result = false
		}
		break
	}
	return

}
func (or TableInfoMeta) DataBaseExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var (
		f1    any
		event = "[oracleDataBaseExist]"
	)
	for _, v := range []string{"all_users", "dba_users"} {
		result.BaseResult.Sql = fmt.Sprintf("SELECT  count(1) as `sum` FROM %v WHERE username = '%v'", v, s.TableInfo.Schema)
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil || f1 == nil {
			continue
		}
		if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
			result.Result = true
		}
		break
	}
	return
}
